<template>
	<div class="container">
		<table>
			<thead>
				<tr>
					<th v-for="(item, index) in title" :key="index">
						{{ item }}
					</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="item in list" :key="item.id">
					<td v-for="(value, key) in item" :key="key">
						<template v-if="key !== 'count'">{{ value }}</template>
						<template v-else>
							<button @click="item.count ? item.count-- : item.count">-</button>
							<input type="text" :value="item.count" @input="(e) => checkInp(e, item)" @blur="onBlur"/>
							<button @click="item.count++">+</button>
						</template>
					</td>
					<td>{{ item.count * item.price }}</td>
				</tr>
			</tbody>
		</table>
		<div class="total">总价为：{{ getSum }}</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			title: {
				id: "序号",
				name: "书名",
				price: "单价",
				count: "数量",
				total: "合计",
			},
			list: [
				{
					id: 1,
					name: "水浒传",
					price: 107,
					count: 0,
				},
				{
					id: 2,
					name: "西游记",
					price: 192,
					count: 0,
				},
				{
					id: 3,
					name: "三国演义",
					price: 219,
					count: 0,
				},
				{
					id: 4,
					name: "红楼梦",
					price: 178,
					count: 0,
				},
			],
		};
	},
	computed: {
		getSum() {
			return this.list.reduce(
				(pre, current) => pre + current.count * current.price, 0);
		},
	},
    methods: {
        checkNum (arr) {
            return arr.every(item => !isNaN(item.count));
        },
        checkInp (e, item) {
            if (!isNaN(e.target.value) && e.target.value >= 0) {
                item.count = Number(e.target.value);
            }
        },
        onBlur () {
            this.list = this.list.concat();
        }

    }
};
</script>

<style scoped>
.container {
	margin-bottom: 50px;
}
table {
	border-left: 1px solid rgb(32, 25, 25);
	border-top: 1px solid rgb(32, 25, 25);
	border-spacing: 0;
}
th {
	text-align: center;
}
th,
td {
	border-bottom: 1px solid rgb(32, 25, 25);
	border-right: 1px solid rgb(32, 25, 25);
	width: 120px;
	height: 30px;
	line-height: 30px;
}
input {
	width: 60px;
}
.number {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
button {
	width: 20px;
	height: 20px;
}
</style>